/**==============================================================================
            Copyright (c) 2013 Moritz Hader, Marcel Schrder
            All Rights Reserved.

	@file  IS_Connector.java

	@brief Handles the HTTP communication with the IS

  This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
==============================================================================*/

package de.ibm.dhbw.backing.dataHolding;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

/**
 * @author Marcel Schroeder - marcel_schroeder89@hotmail.com
 */
public class IS_Connector {
	private static final Logger Log = Logger.getLogger(IS_Connector.class.getCanonicalName());
	//----------- Properties and Constructor -----------//

	private String ip = "localhost";
	private String port = "8080";
	
	protected IS_Connector(String ip, String port) {
		if(null != ip && !ip.isEmpty()) {
			this.ip = ip;
		}
		if(null != port && !port.isEmpty()) {
			this.port = port;
		}
	}
	
	
	//----------- Internal Methods -----------//

	//ready
	//successfully tested
	/**
	 * Sends a HTTP POST request to the IS and catches the related answer
	 * @param requestURL The URL to which the request should be send
	 * @param requestJSON The JSON String which represents the request
	 * @return The answer of the IS in String form
	 */
	private String firePostHTTPRequest(String requestURL, String requestJSON) {
		
		/*<<<TEST AUSGABE>>>*/ Log.info("Cl: IS_Connector, Me: firePostHTTPRequest, Pr: requestURL :" + requestURL);
		/*<<<TEST AUSGABE>>>*/ Log.info("Cl: IS_Connector, Me: firePostHTTPRequest, Pr: requestJSON :" + requestJSON);
		
		URL url = null;
		HttpURLConnection connection = null;
		try {
			url = new URL(requestURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestProperty("Content-Length", String.valueOf(requestJSON.length()));
			OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
			wr.write(requestJSON);
			wr.flush();
			wr.close();
			BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder answer = new StringBuilder();
			for(String line; null != (line = rd.readLine());) {
				answer.append(line);
			}
			
			/*<<<TEST AUSGABE>>>*/ Log.info("Cl: IS_Connector, Me: firePostHTTPRequest, Pr: answer :" + answer);
			
			return answer.toString();
		} catch (MalformedURLException e) {
			Log.severe("MalformedURLException in IS_Connector - firePostHTTPRequest");
			e.printStackTrace();
		} catch (IOException e) {
			Log.severe("IOException in IS_Connector - firePostHTTPRequest");
			e.printStackTrace();
		}
		return "Error";
	}
	
	//ready
	//successfully tested
	/**
	 * Sends a HTTP GET request to the IS and catches the related answer
	 * @param requestURL The URL to which the request should be send
	 * @return The answer of the IS in String form
	 */
	private String fireGetHTTPRequest(String requestURL) {
		
		/*<<<TEST AUSGABE>>>*/ Log.info("Cl: IS_Connector, Me: fireGetHTTPRequest, Pr: requestURL :" + requestURL);
		
		URL url = null;
		HttpURLConnection connection = null;
		try {
			url = new URL(requestURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoInput(true);
			connection.setDoOutput(false);
			BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder answer = new StringBuilder();
			for(String line; null != (line = rd.readLine());) {
				answer.append(line);
			}
			
			/*<<<TEST AUSGABE>>>*/ Log.info("Cl: IS_Connector, Me: fireGetHTTPRequest, Pr: answer :" + answer);
			
			return answer.toString();
		} catch (MalformedURLException e) {
			Log.severe("MalformedURLException in IS_Connector - fireGetHTTPRequest");
			e.printStackTrace();
		} catch (IOException e) {
			Log.severe("IOException in IS_Connector - fireGetHTTPRequest");
			e.printStackTrace();
		}
		return "Error";
	}
	
	
	//----------- External Methods -----------//

	//ready
	//successfully tested
	/**
	 * Constructs the URL for requesting the Markers from the IS and initiates a HTTP GET request to this URL
	 * @return The answer to the HTTP GET request to the IS
	 */
	protected String fetchMarkers() {
		String requestURL = "http://" + this.ip + ":" + this.port + "/marker"; 
		return this.fireGetHTTPRequest(requestURL);
	}
	
	//ready
	//successfully tested
	/**
	 * Constructs the URL for requesting the Markers from the IS and initiates a HTTP POST request to this URL
	 * @param markersInJSON A JSON String which contains the request itself
	 * @return The answer to the HTTP GET request to the IS
	 */
	protected String fetchElements(String markersInJSON) {
		String requestURL = "http://" + this.ip + ":" + this.port + "/surround";
		return this.firePostHTTPRequest(requestURL, markersInJSON);
	}	
}
